package demo.jms.config;

import demo.jms.consumer.MyConsumer;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

/**
 * Created by alex on 15-5-13.
 */
@Configuration
@ComponentScan(basePackages = "demo.jms")
public class JmsConfig {

    /**
     * SingleConnectionFactory对于建立JMS服务器链接的请求会一直返回同一个链接，并且会忽略Connection的close方法调用。
     * @return
     */
    @Bean
    public SingleConnectionFactory singleConnectionFactory() {
//        return new SingleConnectionFactory();
        return new SingleConnectionFactory(activeMQConnectionFactory());
//        return new SingleConnectionFactory(pooledConnectionFactory());
    }

    /**
     * 由ActiveMQ提供的ConnectionFactory
     * @return
     */
    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL("tcp://192.168.1.28:61616");
        return connectionFactory;
    }

    @Bean
    public PooledConnectionFactory pooledConnectionFactory() {
        PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory());
        pooledConnectionFactory.setMaxConnections(20);
        return pooledConnectionFactory;
    }

    @Bean
    @Qualifier("mq_queue")
    public ActiveMQQueue activeMQQueue() {
        return new ActiveMQQueue("mq_queue");
    }

    @Bean
    public ActiveMQTopic activeMQTopic() {
        return new ActiveMQTopic("mq_topic");
    }

    @Bean
    public JmsTemplate jmsTemplate() {
        return new JmsTemplate(singleConnectionFactory());
    }

    // message listener
    @Bean
    public MyConsumer myConsumer(){
        return new MyConsumer();
    }

    //listener container
    @Bean
    public DefaultMessageListenerContainer defaultMessageListenerContainer(){
        DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
        container.setConnectionFactory(singleConnectionFactory());
        container.setDestination(activeMQQueue());
        container.setMessageListener(myConsumer());
        return container;
    }
}
